﻿using AutoMapper;
using BLL;
using BLL.Interface;
using DAL;
using DAL.Models;
using DAL.Models.DTO;
using ExpressManagement.Areas.BackSys.ServiceTools;
using ExpressManagement.Areas.BackSys.ServiceTools.Redis;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace ExpressManagement.Areas.BackSys.Controllers
{
    [Area("BackSys")]
    //[Route("api/[controller]")]
    //[ApiController]
    public class WelcomeController : BaseController
    {

        private readonly IMemoryCache _memoryCache;
        private readonly IUserinfoImpl _userinfoImpl;
        private readonly IDeliverymanImpl _deliverymanImpl;
        private readonly IManagerImpl _managerImpl;
        private readonly IBagInfoImpl _bagInfoImpl;
        private readonly IComplaintBagImpl _complaintBagImpl;
        public WelcomeController(IMemoryCache _memoryCache, RedisHelper redisHelper,IBagInfoImpl bagInfoImpl,IComplaintBagImpl complaintBagImpl,  IUserinfoImpl userinfoImpl,IDeliverymanImpl deliverymanImpl ,IManagerImpl managerImpl,  ExpressDBContext _dbContext, IHttpContextAccessor httpContextAccessor, DbContextOptions<ExpressDBContext> _dbContextoptions, IMapper mapper, SignalRSender signalRSender)
            : base(mapper: mapper, signalRSender: signalRSender, httpContextAccessor: httpContextAccessor, _memoryCache: _memoryCache, redisHelper: redisHelper, _dbContext: _dbContext, dbContextOptions: _dbContextoptions)

        {
            _bagInfoImpl = bagInfoImpl;
            _complaintBagImpl = complaintBagImpl;
            _userinfoImpl = userinfoImpl;
            _deliverymanImpl = deliverymanImpl;
            _managerImpl = managerImpl;
        }
        // GET: BackSys/Welcome
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            //ViewBag.ReturnUrl = ReturnUrl;
            return View();
        }

        public async Task<IActionResult> IndexPart()
        {
            //ViewBag.ReturnUrl = ReturnUrl;
            return PartialView();
        }
        [HttpPost]
        public async Task<IActionResult> LogOut()
        {
            HttpContext.Session.Clear();
            var loginType = GetStringFromSession("loginType");
            var userName = GetStringFromSession("userName");
            var userId = GetStringFromSession("userId");
            var scheme = string.Empty;
            if(userName != null&& userId != null)
            {
                //IList<Claim> claims = new List<Claim>();
                //claims.Add(new Claim(ClaimTypes.Name, userName));
                //claims.Add(new Claim(ClaimTypes.SerialNumber, userId));
                //switch (loginType)
                //{
                //    case "用户":
                //        scheme = Resource.ActorUser;
                //        break;
                //    case "管理员":
                //        scheme = Resource.ActorManager;
                //        break;
                //    case "快递员":
                //        scheme = Resource.ActorDeliveryman;
                //        break;
                //    default:
                //        break;
                //}
                //claims.Add(new Claim(ClaimTypes.Actor, scheme));
                 await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
      
                ResetMQLink();

            return Json(1);
        }

        [HttpPost]
        public PartialViewResult ChangePage(string action,string controller)
        {
            //var action = Request.Query["Action"].ToString().Trim().ToString();
            //var controller = Request.Query["Controller"].ToString().Trim().ToString();
            return PartialView(action, controller);
        }

        [HttpPost]
        public async Task<IActionResult> Update([FromForm] UserDTO entity)
        {

            switch (LoginType)
            {
                case "用户":
                    UserInfo user = _mapper.Map<UserInfo>(entity);
                    user.UpdateTime = DateTime.Now;
                    //UserInfo user = new UserInfo()
                    //{
                    //    Id = Convert.ToInt32(Request.Query["Id"].ToString().Trim()),
                    //    UserName = Request.Form["UserName"],
                    //    UserPass = Request.Query["UserPass"],
                    //    TrueName = Request.Query["TrueName"],
                    //    Phone = Request.Query["Phone"],
                    //    Idcard = Request.Query["Phone"],
                    //    Email = Request.Query["Phone"],
                    //    ContactAddress = Request.Query["Address"],
                    //    UpdateTime = DateTime.Now
                    //};
                    if (_userinfoImpl.Update(user.Id, user))
                    {
                        RemoveRedisCacheEntity(EntityUserInfo, TypePage, "用户");
                        RemoveRedisCacheEntity(EntityUserInfo, TypePage, "快递员");
                        RemoveRedisCacheEntity(EntityUserInfo, TypePage, "管理员");
                        return Json(1);
                    }
                    break;
                case "管理员":
                    Manager manager = _mapper.Map<Manager>(entity);
                    manager.UpdateTime = DateTime.Now;
                    //Manager manager = new Manager()
                    //{
                    //    Id = Convert.ToInt32(Request.Query["Id"].ToString().Trim()),
                    //    UserName = Request.Query["UserName"].ToString().Trim(),
                    //    UserPass = Request.Query["UserPass"].ToString().Trim(),
                    //    TrueName = Request.Query["TrueName"].ToString().Trim(),
                    //    Phone = Request.Query["Phone"].ToString().Trim(),
                    //    Idcard = Request.Query["Phone"].ToString().Trim(),
                    //    UpdateTime = DateTime.Now
                    //};
                    if (_managerImpl.Update(manager.Id, manager))
                    {
                        RemoveRedisCacheEntity(EntityManager, TypePage, "用户");
                        RemoveRedisCacheEntity(EntityManager, TypePage, "快递员");
                        RemoveRedisCacheEntity(EntityManager, TypePage, "管理员");
                        return Json(1);
                    }
                        break;
                case "快递员":
                    Deliveryman deliveryman = _mapper.Map<Deliveryman>(entity);
                    deliveryman.UpdateTime = DateTime.Now;
                    //Deliveryman deliveryman = new Deliveryman()
                    //{
                    //    Id = Convert.ToInt32(Request.Query["Id"].ToString().Trim()),
                    //    UserName = Request.Query["UserName"].ToString().Trim(),
                    //    UserPass = Request.Query["UserPass"].ToString().Trim(),
                    //    TrueName = Request.Query["TrueName"].ToString().Trim(),
                    //    Phone = Request.Query["Phone"].ToString().Trim(),
                    //    Idcard = Request.Query["Phone"].ToString().Trim(),
                    //    UpdateTime = DateTime.Now
                    //};
                    if (_deliverymanImpl.Update(deliveryman.Id, deliveryman))
                    {
                        RemoveRedisCacheEntity(EntityDeliveryman, TypePage, "用户");
                        RemoveRedisCacheEntity(EntityDeliveryman, TypePage, "快递员");
                        RemoveRedisCacheEntity(EntityDeliveryman, TypePage, "管理员");
                        return Json(1);
                    }
                    break;
                default:
                    break;
            }
            return Json(0);

        }

        //[HttpPost]
        //[ResponseCache(Duration = 10)]
        public async Task<IActionResult> SelfInfomation()
        {
            if (string.IsNullOrEmpty(GetStringFromSession("loginType")))
            {
                return RedirectToAction("Login", "Home");
            }

            switch (GetStringFromSession("loginType"))
            {
                case "管理员":
                case "快递员":
                    SetInt32InSession("bagNums", _bagInfoImpl.GetList().Count);
                    SetInt32InSession("complaintNums", _complaintBagImpl.GetList().Count);
                    break;

                case "用户":
                    UserInfo? user = GetObjectFromSession<UserInfo>("detail");
                    SetInt32InSession("bagNums", _bagInfoImpl.GetList(user.UserName, user.Phone).Select(o=>o.Count).Sum());
                    SetInt32InSession("complaintNums", _complaintBagImpl.GetList(user.UserName, user.Phone).Count);
                    break;
                default:
                    break;
            }
            return PartialView();
        }
    }
}